package com.sicnu.cheer.leaugebar.managemodule.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.sicnu.cheer.generalmodule.activity.BaseActivity;
import com.sicnu.cheer.generalmodule.adapter.base.CommonAdapter;
import com.sicnu.cheer.generalmodule.adapter.viewholder.CommonViewHolder;
import com.sicnu.cheer.generalmodule.bean.JoinLeagueBean;
import com.sicnu.cheer.generalmodule.bean.MyUser;
import com.sicnu.cheer.generalmodule.util.NetWorkUtil;
import com.sicnu.cheer.generalmodule.util.UIHelper;
import com.sicnu.cheer.leaugebar.managemodule.R;
import com.sicnu.cheer.xlistview.view.XListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;

public class FilterResumeActivity extends BaseActivity implements View.OnClickListener {

    private ImageView rightIV;
    private LinearLayout noResultLL;

    private XListView listView;
    private CommonAdapter mAdapter;
    private List<JoinLeagueBean> resumeList;
    private ProgressDialog progressDialog;
    private int pageSize = 10;
    private int skip = 0;
    private int state = -1;
    private Map<Integer, Integer> stateMap = new HashMap<>();


    private PopupWindow mPopWindow;

    @Override
    public int getContentViewId() {
        return R.layout.activity_filter_resume;
    }

    @Override
    protected void initData() {
        super.initData();
        resumeList=new ArrayList<>();
        progressDialog = new ProgressDialog(mThis);
        progressDialog.setMessage("加载中...");
        stateMap.put(0, R.mipmap.un_read);
        stateMap.put(1, R.mipmap.passed);
        stateMap.put(2, R.mipmap.failed);
    }

    @Override
    protected void initView() {
        super.initView();
        findViewById(R.id.back).setOnClickListener(this);
        ((TextView) findViewById(R.id.title)).setText("审批申请表");
        rightIV = ((ImageView) findViewById(R.id.title_right_button));
        rightIV.setImageResource(R.mipmap.filter);
        rightIV.setOnClickListener(this);

        noResultLL = ((LinearLayout) findViewById(R.id.no_data_ll));
        noResultLL.setVisibility(View.GONE);
        listView = ((XListView) findViewById(R.id.data_xlv));
    }

    @Override
    protected void afterViews() {
        super.afterViews();
        setXListView();
        //请求服务器上的数据
        requestDataFromBmob(true);

        //将获取到的数据填充界面
        listView.setAdapter(mAdapter = new CommonAdapter<JoinLeagueBean>(
                getApplicationContext(), resumeList, R.layout.item_resume) {
            @Override
            public void convert(CommonViewHolder helper, JoinLeagueBean item) {
                if (item != null) {
                    helper.setImageResource(R.id.resume_state_iv, stateMap.get(item.getPass()));
                    MyUser myUser = item.getMyUser();
                    if (myUser != null) {
                        helper.setImageByUrl(R.id.resume_head_iv, myUser.getHeadPic());
                        helper.setText(R.id.resume_username_tv, myUser.getNick());
                        helper.setText(R.id.resume_brief_info_tv, String.valueOf(myUser.getGrade() + "-") + myUser.getMajor());
                    }
                }
            }

        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mThis, ResumeDetailActivity.class);
                intent.putExtra("resume", resumeList.get(position - 1));
                intent.putExtra("isApproval",true);//是否是审批
                startActivityForResult(intent,1);
            }
        });
    }

    private void setXListView() {
        listView.setPullLoadEnable(true);
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                pageSize = 10;
                skip = 0;
                requestDataFromBmob(true);
            }

            @Override
            public void onLoadMore() {
                pageSize += 10;
                skip += 10;
                requestDataFromBmob(false);
            }
        });
    }

    private void requestDataFromBmob(final boolean isRefresh) {
        resetState();
        if (!NetWorkUtil.isConnect(mThis)) {
            UIHelper.ToastMessage(mThis, "没有网络，请设置网络");
            return;
        }
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
        BmobQuery<JoinLeagueBean> query = new BmobQuery<>();
        if (state!=-1) {
            query.addWhereEqualTo("pass", state);
        }
        query.addWhereEqualTo("leagueBean", MyUser.getCurrentUser(mThis,MyUser.class).getLeague());//只能查看用户当前所在社团的申请
        query.setLimit(pageSize);
        query.setSkip(skip);
        query.order("-createdAt");
        query.include("myUser,leagueBean");
        query.findObjects(mThis, new FindListener<JoinLeagueBean>() {
            @Override
            public void onSuccess(List<JoinLeagueBean> list) {
                stopXListView(isRefresh);
                if (list==null||list.size()==0){
                    setNoResultState(isRefresh);
                }else {
                    if (isRefresh){
                        resumeList.clear();
                    }
                    resumeList.addAll(list);
                    mAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(int i, String s) {
                stopXListView(isRefresh);
                UIHelper.ToastMessage(mThis, "查询失败：" + s);
            }
        });

    }

    private void resetState() {
        noResultLL.setVisibility(View.GONE);
        listView.setVisibility(View.VISIBLE);
        listView.setPullLoadEnable(true);
    }

    private void setNoResultState(boolean isRefresh) {
        if (isRefresh){
            noResultLL.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
        }else {
            listView.setPullLoadEnable(false);
            UIHelper.ToastMessage(mThis, "没有更多数据了");
        }
    }

    private void stopXListView(boolean isRefresh) {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        if (isRefresh){
            listView.stopRefresh();
        }else {
            listView.stopLoadMore();
        }

    }
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.back) {
            onBackPressed();
        }else if (v.getId()==R.id.title_right_button){
            popUpWindow(rightIV);
        }else if (v.getId()==R.id.pop_up_window){
            closePopUpWindow();
        }else if (v.getId()==R.id.select_all){
            afterSelected(-1);
        }else if (v.getId()==R.id.select_unread){
            afterSelected(0);
        }else if (v.getId()==R.id.select_passed){
            afterSelected(1);
        }else if (v.getId()==R.id.select_failed){
            afterSelected(2);
        }
    }

    /**
     * 执行弹出框后的操作
     * @param i
     */
    private void afterSelected(int i) {
        state=i;
        closePopUpWindow();
        requestDataFromBmob(true);
    }

    /**
     * 弹出框根据申请表状态选择查看内容
     * @param v
     */
    private void popUpWindow(ImageView v) {
        if (mPopWindow==null) {
            //设置contentView
            View contentView = LayoutInflater.from(mThis).inflate(R.layout.layout_pop_window, null);
            mPopWindow = new PopupWindow(contentView,
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
            mPopWindow.setContentView(contentView);
            contentView.findViewById(R.id.select_all).setOnClickListener(this);
            contentView.findViewById(R.id.select_unread).setOnClickListener(this);
            contentView.findViewById(R.id.select_passed).setOnClickListener(this);
            contentView.findViewById(R.id.select_failed).setOnClickListener(this);
            //显示PopupWindow
            mPopWindow.setOutsideTouchable(true);
            mPopWindow.setBackgroundDrawable(new ColorDrawable());
            mPopWindow.showAsDropDown(v);
        }else {
            mPopWindow.showAsDropDown(v);
        }
    }

    private void closePopUpWindow() {
        if (mPopWindow != null) {
            if (mPopWindow.isShowing()) {
                mPopWindow.dismiss();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode==1){
            skip=0;
            requestDataFromBmob(true);
        }
    }
}
